package com.zfei.gfb.device;

import com.zfei.gfb.core.Conf;
import com.zfei.gfb.util.Gsons;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.Duration;
import java.util.Objects;

/**
 * @author fgh
 */
public class InboxConf {

    private static final Logger logger = LoggerFactory.getLogger(InboxConf.class);

    private int limit = 10000;

    private int fetch = 100;

    private Duration timeout = Duration.ofHours(72);

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public int getFetch() {
        return fetch;
    }

    public void setFetch(int fetch) {
        this.fetch = fetch;
    }

    public Duration getTimeout() {
        return timeout;
    }

    public void setTimeout(Duration timeout) {
        this.timeout = timeout;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        InboxConf inboxConf = (InboxConf) o;
        return limit == inboxConf.limit &&
                fetch == inboxConf.fetch &&
                Objects.equals(timeout, inboxConf.timeout);
    }

    @Override
    public int hashCode() {
        return Objects.hash(limit, fetch, timeout);
    }

    @Scheduled(cron = "${inbox.conf.run:30 */10 * * * ?}")
    public void run() {
        try {
            String text = Conf.getString("InboxConf");
            if (StringUtils.isNotBlank(text)) {
                InboxConf inboxConf = Gsons.fromJson(text.trim(), InboxConf.class);
                if (!this.equals(inboxConf)) {
                    BeanUtils.copyProperties(inboxConf, this);
                    logger.info("InboxConf: {}", Gsons.toJson(this));
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}
